<template>
  <div>
    <el-button type="primary" @click="handleAddProd">添加商品</el-button>
  </div>
  <div>
    <el-form :inline="true" :model="searForm" class="demo-form-inline">
      <el-form-item label="商品名称">
        <el-input
          v-model="searForm.keyWord"
          placeholder="请输入商品名称"
          clearable
        />
      </el-form-item>

      <el-form-item label="商品ID">
        <el-input
          v-model="searForm.typeId"
          placeholder="请输入商品ID"
          clearable
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onQuery">查询</el-button>
        <el-button
          type="danger"
          @click="delAll"
          :disabled="multipleSelection.length == 0"
          >批量删除</el-button
        >
      </el-form-item>
    </el-form>
  </div>
  <div>
    <el-table
      :data="tableData"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="prodId" label="商品ID" width="55" />
      <el-table-column prop="prodSpu" label="商品SPU" width="100" />
      <el-table-column prop="prodName" label="商品名称" width="100" />
      <el-table-column prop="prodImage" label="商品图片" width="100">
        <template #default="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.prodImage"
          />
        </template>
      </el-table-column>
      <el-table-column prop="prodStatus" label="状态" width="55">
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.prodStatus == 0">下架</el-tag>
          <el-tag type="primary" v-if="scope.row.prodStatus == 1">上架</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="checkStatus" label="审核" width="100">
        <template #default="scope">
          <span type="success" v-if="scope.row.checkStatus == 0"></span>
          <el-tag type="success" v-if="scope.row.checkStatus == 1">通过</el-tag>
          <el-tag type="danger" v-if="scope.row.checkStatus == 2">驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200" />
      <el-table-column prop="typeName" label="分类名称" width="100" />
      <el-table-column prop="brandName" label="品牌名称" width="100" />
      <el-table-column prop="unitName" label="单位" width="55" />
      <el-table-column prop="tagName" label="标签" width="55" />
      <el-table-column prop="dictLable" label="商品类型" width="100" />
      <el-table-column prop="apprName" label="供应商名称" width="100" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleProd(scope.row)">
            商品
          </el-button>
          <el-button
            size="small"
            v-if="scope.row.prodStatus == 0"
            type="success"
            @click="handleAtta(scope.row)"
          >
            商品附件
          </el-button>

          <el-button
            size="small"
            v-if="scope.row.checkStatus == 0"
            type="success"
            @click="showCheck(scope.row)"
          >
            审核
          </el-button>

          <el-button
            type="primary"
            v-if="scope.row.prodStatus == 1"
            size="small"
            @click="handleBuy(scope.row)"
          >
            购买
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div>
    <el-pagination
      v-model:current-page="searForm.pageNum"
      v-model:page-size="searForm.pageSize"
      :page-sizes="[2, 4, 6, 8]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  <div>
    <el-dialog v-model="dialogFormVisible" title="商品添加" width="500">
      <el-form :model="form">
        <el-form-item label="商品类型" :label-width="formLabelWidth">
          <el-radio-group v-model="form.prodKind">
            <el-radio :value="0">实物商品</el-radio>
            <el-radio :value="1">虚拟商品</el-radio>
            <el-radio :value="2">卡密/网盘</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="商品分类" :label-width="formLabelWidth">
          <el-tree-select
            v-model="form.typeId"
            :data="typeListTree"
            check-strictly
            :render-after-expand="false"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="form.prodName" autocomplete="off" />
        </el-form-item>

        <el-form-item label="商品Spu" :label-width="formLabelWidth">
          <el-input v-model="form.prodSpu" autocomplete="off" />
        </el-form-item>

        <el-form-item label="商品品牌" :label-width="formLabelWidth">
          <el-select v-model="form.brandId" placeholder="请选择品牌">
            <el-option
              v-for="item in brandAll"
              :label="item.brandName"
              :value="item.brandId"
              :key="item.brandId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="商品单位" :label-width="formLabelWidth">
          <el-select v-model="form.unitId" placeholder="请选择商品单位">
            <el-option
              v-for="item in unitListAll"
              :label="item.unitName"
              :value="item.unitId"
              :key="item.unitId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="商品标签" :label-width="formLabelWidth">
          <el-select v-model="form.tagId" placeholder="请选择商品标签">
            <el-option
              v-for="item in tagListAll"
              :label="item.tagName"
              :value="item.tagId"
              :key="item.tagId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="供应商" :label-width="formLabelWidth">
          <el-select v-model="form.apprId" placeholder="请选择供应商">
            <el-option
              v-for="item in ApprListAll"
              :label="item.apprName"
              :value="item.apprId"
              :key="item.apprId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="商品缩略图" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:10010/shop/type/uploadFile"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="headers"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">放弃</el-button>
          <el-button type="primary" @click="onAddProd"> 添加 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <!-- 商品附件表------------------------------------------------------------------------------------->
  <div>
    <el-dialog v-model="atta" ref="ruleFormRef" title="商品附件" width="800">
      <el-form :model="attaForm">
        <el-form-item label="商品轮播图" :label-width="formLabelWidth">
          <el-upload
            v-model:file-list="fileList"
            action="http://localhost:10010/shop/type/uploadFile"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :headers="headers"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="商品视频" :label-width="formLabelWidth">
          <el-upload
            v-model:file-list="videoList"
            class="upload-demo"
            action="http://localhost:10010/shop/type/uploadFile"
            :on-change="handleChange"
            :headers="headers"
            :before-upload="beforeAvatarUpload"
          >
            <el-button type="primary">Click to upload</el-button>
            <template #tip>
              <div class="el-upload__tip">
                作用于商品详情页顶部轮措的视频介绍,最大限制20MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="上架时间" :label-width="formLabelWidth">
          <el-radio-group v-model="attaForm.upType">
            <el-radio :value="0">立即上架</el-radio>
            <el-radio :value="1">定时上架</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label=""
          v-if="attaForm.upType == 1"
          :label-width="formLabelWidth"
        >
          <el-date-picker
            v-model="attaForm.upTime"
            type="datetime"
            placeholder="请选择上架时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="定时下架" :label-width="formLabelWidth">
          <el-switch
            v-model="attaForm.downType"
            size="large"
            active-text="Open"
            inactive-text="Close"
            :active-value="0"
            :inactive-value="1"
          />
        </el-form-item>

        <el-form-item
          label=""
          v-if="attaForm.downType == 0"
          :label-width="formLabelWidth"
        >
          <el-date-picker
            v-model="attaForm.downTime"
            type="datetime"
            placeholder="请选择下架时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="atta = false">放弃</el-button>
          <el-button type="primary" @click="onsubmitAddAtta"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 商品附件表------------------------------------------------------------------------------------->
  <!-- 以下是商品审核功能表单----------------------------------------------------------------------- -->
  <div>
    <el-dialog v-model="checkForm" title="商品审核" width="500">
      <el-form :model="form">
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="form.prodName" disabled autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品种类" :label-width="formLabelWidth">
          <el-select v-model="form.prodKind" disabled placeholder="请选择">
            <el-option label="实物商品" :value="0" />
            <el-option label="虚拟商品" :value="1" />
            <el-option label="卡密/网盘" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品封面" :label-width="formLabelWidth">
          <el-image
            :src="form.prodImage"
            style="width: 120px; height: 120px"
          ></el-image>
        </el-form-item>
        <el-form-item label="审核状态" :label-width="formLabelWidth">
          <el-radio-group v-model="form.checkStatus">
            <el-radio :value="1">审核通过</el-radio>
            <el-radio :value="2">审核驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核原因" :label-width="formLabelWidth">
          <el-input
            v-model="form.checkReason"
            type="textarea"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="checkForm = false">放弃</el-button>
          <el-button type="primary" @click="onCheckStatus"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 以↑是商品审核功能表单----------------------------------------------------------------------- -->
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import {
  getProdList,
  addProd,
  getSelectTypeList,
  getBrandListAll,
  getUnitListAll,
  getTagListAll,
  getApprListAll,
  deleteAll,
  addProdAtta,
  checkProd,
} from "../api/api";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, type UploadProps } from "element-plus";
import type { UploadUserFile } from "element-plus";
import { useRouter } from "vue-router";
import { tr } from "element-plus/es/locales.mjs";

const router = useRouter();
//多图上传-------------------------------------------
const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const checkForm = ref(false);

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
//以上为多图上传---------------------------

//视频上传------------------------------------------------------
const videoList = ref<UploadUserFile[]>([]);

const handleChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
  videoList.value = videoList.value.slice(-3);
};

//上传视频钱校验是否为视频类型
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "video/mp4") {
    ElMessage.error("上传文件的格式必须为视频");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("上传视频不能大于2MB!");
    return false;
  }
  return true;
};

//以上是上传视频------------------------------------------------
const atta = ref(false);

const attaForm = ref({
  downTime: null,
  downType: 0,
  imageList: [],
  prodId: 0,
  prodVideo: null,
  upTime: null,
  upType: 0,
});
const imageUrl = ref("");
const headers = {
  token: window.sessionStorage.getItem("token"),
};
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = response.data;
  form.value.prodImage = imageUrl.value;
};

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

//添加商品附件
const onsubmitAddAtta = () => {
  attaForm.value.imageList = [];
  //多图片
  fileList.value.forEach((item) => {
    // attaForm.value.imageList.push(item.url);
    let img = {
      imageUrl: item.response.data,
    };
    attaForm.value.imageList.push(img);
  });
  //商品视频放入表单
  if (videoList.value.length > 0) {
    attaForm.value.prodVideo = videoList.value[0].response.data;
  }

  addProdAtta(attaForm.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      atta.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const form = ref({
  prodSpu: null,
  prodName: null,
  typeId: null,
  brandId: null,
  unitId: null,
  tagId: null,
  apprId: null,
  prodImage: null,
  prodStatus: null,
  prodKind: null,
  createTime: null,
  createBy: null,
  updateTime: null,
  updateBy: null,
  typeName: null,
  brandName: null,
  unitName: null,
  tagName: null,
  dictLable: null,
  apprName: null,
  kindId: null,
  checkStatus: null,
  checkReason: null,
});

const resetForm = () => {
  form.value = {
    checkReason: null,
    kindId: null,
    prodSpu: null,
    prodName: null,
    typeId: null,
    brandId: null,
    unitId: null,
    tagId: null,
    apprId: null,
    prodImage: null,
    prodStatus: null,
    prodKind: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    typeName: null,
    brandName: null,
    unitName: null,
    tagName: null,
    dictLable: null,
    apprName: null,
    checkStatus: null,
  };
  imageUrl.value = "";
};

const multipleSelection = ref<any[]>([]);
const tableData = ref([]);
const total = ref(0);
const searForm = ref({
  pageNum: 1,
  pageSize: 2,
  typeId: null,
  keyWord: null,
});

const loadList = () => {
  getProdList(searForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searForm.value.pageSize = val;
  loadList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searForm.value.pageNum = val;
  loadList();
};

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
  console.log(multipleSelection.value);
};

const delAll = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.error("请选择要删除的信息");
    return;
  }
  console.log(multipleSelection.value);
  ElMessageBox.confirm("删除后信息无法恢复，确定删除吗?", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "放弃",
    type: "warning",
  })
    .then(() => {
      //批量删除
      deleteAll(multipleSelection.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {});
};

//添加弹出层
const handleAddProd = () => {
  dialogFormVisible.value = true;
};
//添加事件
const onAddProd = () => {
  if (form.value.prodSpu == null || form.value.prodSpu == "") {
    ElMessage.error("商品Spu不能为空");
    return;
  }
  imageUrl.value = form.value.prodImage;
  addProd(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      resetForm();
      dialogFormVisible.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//商品
const handleProd = (row: any) => {
  console.log(row);
};
//购买商品
const handleBuy = (row: any) => {
  console.log(row);
  let prod = JSON.stringify(row);
  sessionStorage.setItem("buy", prod);
  router.push("/home/buy");
};
//商品附件
const handleAtta = (row: any) => {
  console.log(row);
  attaForm.value.prodId = row.prodId;
  atta.value = true;
};

//条件查询
const onQuery = () => {
  console.log("submit!");
  loadList();
};

const onCheckStatus = () => {
  if (form.value.checkStatus == null) {
    ElMessage.error("请选择审核状态");
    return;
  }
  if (form.value.checkStatus == 2) {
    if (form.value.checkReason == null || form.value.checkReason == "") {
      ElMessage.error("请输入审核驳回原因");
      return;
    }
  }
  //提交审核
  checkProd(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("审核成功");
      checkForm.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
const showCheck = (row: any) => {
  Object.assign(form.value, row);
  checkForm.value = true;
};

const typeListTree = ref([]);
const brandAll = ref([]);
const unitListAll = ref([]);
const tagListAll = ref([]);
const ApprListAll = ref([]);
onMounted(() => {
  loadList();
  getSelectTypeList().then((res) => {
    if (res.data.code == 200) {
      typeListTree.value = res.data.data;
    }
  });

  getBrandListAll().then((res) => {
    if (res.data.code == 200) {
      brandAll.value = res.data.data;
    }
  });
  getUnitListAll().then((res) => {
    if (res.data.code == 200) {
      unitListAll.value = res.data.data;
    }
  });
  getTagListAll().then((res) => {
    if (res.data.code == 200) {
      tagListAll.value = res.data.data;
    }
  });
  getApprListAll().then((res) => {
    if (res.data.code == 200) {
      ApprListAll.value = res.data.data;
    }
  });
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
